<template>
    <div id="register">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form :model="registerForm" :rules="addFormRules" class="register-container" size="medium" @keyup.enter.native="handleClick">
                <h3 class="register_title">注册</h3>

                <!-- :error="errorMsg1" 触发事件返回的错误信息  @blur="checkUsername"  鼠标移动触发事件-->
                <el-form-item  :error="errorMsg1"  prop="username" >
                    <el-input type="text" v-model="registerForm.username"  @blur="checkUsername"  autofocus ref="username"
                              auto-complete="off" placeholder="用户名" prefix-icon="el-icon-user-solid" spellcheck="false">
                    </el-input>
                </el-form-item>

                  <el-form-item prop="email" >
                    <el-input type="text" v-model="registerForm.email" autofocus ref="email"
                              auto-complete="off" placeholder="邮箱 " prefix-icon="el-icon-message" spellcheck="false">
                    </el-input>
                </el-form-item>
                
                  <el-form-item prop="mobile" >
                    <el-input type="text" v-model="registerForm.mobile" autofocus ref="mobile"
                              auto-complete="off" placeholder="电话" prefix-icon="el-icon-phone" spellcheck="false">
                    </el-input>
                </el-form-item>

                <el-form-item prop="password">
                    <el-input type="password" v-model="registerForm.password"  show-password autofocus ref="password"
                              auto-complete="off" placeholder="密码" prefix-icon="el-icon-key" v-on:input="change">
                    </el-input>
                </el-form-item>


                <el-form-item style="width: 100%;">
                    <el-checkbox class="service_terms" v-model="checked" >
                        <!-- <span style="color: #409EFF"></span> -->
                        <label style="color: #949493">我已阅读并同意相关服务条款和政策隐私</label>
                    </el-checkbox>
                </el-form-item>
               
                <el-form-item>
                  <el-button type="primary" icon="el-icon-upload" @click="registerFor()">注册账号</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <p class="register-copyright">© 2021 Lemon 版权所有</p>
    </div>
</template>

<script>


export default {
    name: 'Register',
    data() {
        // 验证邮箱的规则
        var checkEmail = (rule,value,cb) =>{
            const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if(regEmail.test(value)){
                //合法的邮箱
                return cb()
            }
            cb(new Error("请输入合法的邮箱"))
        };
        //验证手机号码的规则
        var checkMobile = (rule,value,cb) =>{
            const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/ 
            if (regMobile.test(value)) { 
                //合法的手机号码
                return cb() 
            }
            cb(new Error('手机号码格式不正确'))     
        };
       // 后台验证用户名是否存在
        var checkUsername = (rule, value, callback) => {
            // this.usernameFor(value);//调用后台处理
            // console.log("我们打的"+callback);
            //  return callback();
            this.usernameFor(value).then(res =>{
                console.log("我们打的"+res);
                if (res.rel && res.data <= 0){
                  callback()
                }else if(res.rel && res.data > 0){
                    callback("注册过儿")
                }else{
                    this.$notify.error({
                        title:'失败',
                        message:'失败了哦',
                        duration:400
                    })
                }
            })


        };


        return {
            //验证规则 rules=
            addFormRules: {
                username: [{required: true, message: '用户名不能为空', trigger: 'change'},
                           { min: 2, max: 10, message: '用户名称长度在2到10个字符', trigger: 'change' },
                           {required: true,pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,message: '姓名不支持特殊字符',trigger: 'change'},
                           {validator:checkUsername,trigger: 'blur'}
                ],
                email: [{required: true, message: '邮箱地址不能为空', trigger: 'change'},
                        {validator:checkEmail,trigger: 'blur'}
                ],
                //validator:****  表示验证器
                //trigger: ‘blur’ 表示“当失去焦点时（光标不显示的时候），触发此提示”
                mobile: [{required: true, message: '电话不能为空', trigger: 'change'},
                         {validator:checkMobile,trigger: 'blur'}
                ],
                password: [{required: true, message: '密码不能为空', trigger: 'change'}]
            },
            checked: true,
            //表单里面的数据
            registerForm: {
                username: '',
                email: '',
                mobile: '',
                password: ''
            },
        }
    },
    methods: {
        //根据用户输入的用户名去后台查询是否有被注册过
        usernameFor() {
            this.errorMsg1 = ""; //校验前需情况错误信息
            this.$axios.post("api/register",{ username: this.registerForm.username}).then(res => {
                console.log("用户校验res", res);
                if (res.data.code === 200) {
                     console.log("后台返回的数据", res.data);
                    return res.data
                }
            });
        },
        registerFor() {
            if (this.registerForm.username === '' || this.registerForm.password === '' || this.registerForm.email === ''|| this.registerForm.mobile === '' ) {
                // 点击注册时，如果用户名或者密码未输入，那么提醒用户输入
                if (this.registerForm.username === '') {
                    this.$message({
                        message: '警告, 用户名未输入哦',
                        type: 'warning'
                    });
                    this.$refs.username.focus();
                } else if(this.registerForm.email === ''){
                    this.$message({
                        message: '警告, 邮箱未输入呀',
                        type: 'warning'
                    });
                    this.$refs.email.focus();
                } else if(this.registerForm.mobile === ''){
                    this.$message({
                        message: '警告, 电话未输入呀',
                        type: 'warning'
                    });
                    this.$refs.mobile.focus();
                } else if(this.registerForm.password === ''){
                    this.$message({
                        message: '警告, 密码未输入呀',
                        type: 'warning'
                    });
                    this.$refs.password.focus();
                } 
            }else {
                //将数据传递给后端
                 this.login()
            }

        },
        change() {
           // 如果监听到输入框发生变化，那么采用用户输入的密码
           this.isInput = true;
        },
        login() { //注册
        //采用这个方式后端接口的方式必须采用对象的方式来接收参数 User
          this.$axios
            .post("api/register", { 
                username: this.registerForm.username, 
                email: this.registerForm.email, 
                password: this.registerForm.password
            })
            .then(res => {
                // console.log("输出response.data.status", res.data.status);
                if (res.data.code === 200) {
                this.$router.push({ path: "/HomePage" });
                } else {
                alert("注册出现异常！");
                }
            });
        },

         
    }
}
</script>

<style scoped >
/* 背景图 */
    #register {
    background-image: url('../assets/picture/background.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    height: 100%;
    width: 100%;
    position: fixed;
}
/* 注册边框图 */
.register-container {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 10% 40% 0 40%;
    width: 20%;
    padding: 25px 30px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
    opacity: 0.7;
}
/* 注册 */
.register_title {
    margin: 0px auto 40px auto;
    text-align: center;
    color: #505458;
}
/* 服务条款 */
.service_terms {
    margin: 0px;
    text-align: left;
    float: left;
}
/* 版权所有 */
.register-copyright {
    color: rgba(175, 168, 168, 0.438);
    padding-bottom: 20px;
    text-align: center;
    position: relative;
    z-index: 1;
}
@media screen and (min-height: 550px) {
    .register-copyright {
        position: absolute;
        bottom: 0;
        right: 0;
        left: 0;
    }
}
</style>

